<?php

namespace app\common\model;

class Order extends BaseModel
{
    protected $table = 'order';
    public function getStatusAttr($value)
    {
        $status = config('status.order');
        return isset($status[$value]) ? $status[$value] : $value;
    }
    public function goods()
    {
        return $this->hasMany('\app\common\model\OrderGoods','order_id');
    }
    public function store()
    {
        return $this->belongsTo('\app\common\model\Store', 'store_id');
    }
    // 发货
    public static function delivery($order_id, $mer_id)
    {
        return self::handleDbTrans(function() use ($order_id, $mer_id){
            $update = [
                'delivery_time' => now(), 'status' => 2
            ];
            if($mer_id)
                return self::where('id', $order_id)->where('mer_id', $mer_id)->update($update);
            else
                return self::where('id', $order_id)->update($update);
        });
    }
    // 近一年的月统计成交金额和数量
    public static function statisticsMonthly($store_id)
    {
        return self::where('status','>',1)
            ->where('store_id',$store_id)
            ->field("SUM(total_price) money, MONTH(add_time) m, year(add_time) y, count(id) count")
            ->group('y,m')
            ->where('add_time', '>=', date("Y-m-d",strtotime("-1 year")))
            ->select();
    }
    // 本月的成交金额和数量
    public static function statisticsDaily($store_id)
    {
        return self::where('status','>', 1)
            ->where('store_id', $store_id)
            ->field("SUM(total_price) money, date(add_time) day, count(id) count")
            ->group('day')
            ->where('add_time', '>=', date("Y-m-d",strtotime("-1 month")))
            ->select();
    }

}